import os
path = os.path.abspath('..')
print(path)

def file_handle(user_data,type='fetch',new_res=None):
    # if type==fetch:
    with open('../config/datawenjia.txt', 'r') as fp:
        ret = []
        tag = False
        for readline in fp:
            if readline.strip() == user_data:
                tag = True
                continue
            if tag and readline.startswith('url'):
                break
            if tag:
                ret.append(readline)
    return ret
    # elif type==rechange:


def fetch(data):
    print('这是查询功能')
    print('用户输入的数据是 %s' % data)
    user_data ='url %s' % data
    print(user_data)
    return file_handle(user_data)

def rechange(data):
    # 将D:/selenium_python/config/datawenjia.txt中 urlmkw 下的
    # https: // star.dai189.com / 修改为 https://www.imooc4.com/
    # [{'bankend':'mkw','url':'https://star.dai189.com/'},{'bankend':'mkw','url':'https://www.imooc5.com/'}]
    print('这是修改函数')
    print('用户传过来的要修改的值是',data) # 用户输入的是字符串、必须转译(相当于有引号)
    # 旧的值
    date_url = data[0]['bankend']  # mkw
    old_url = data[0]['url']
    user_data ='url %s' % date_url  # 拼接字符串 url muk
    print('想要修改的旧地址',old_url)
    # 新的值
    new_url = data[1]['url']
    res = fetch(date_url)  # 传入mkw
    print("来自rechange --->>函数",res)
    new_res = [i.strip() for i in res if i]
    if new_res and old_url in new_res:
        index = new_res.index(old_url)  # 取出被修改对象
        new_res[index] = new_url
        print('列表中的值已经修改了')
    else:
        return '没有被修改的对象'

    # file_handle(user_data,type=rechange,new_res=new_res)
    with open('../config/datawenjia.txt', 'r') as read_fp, \
            open('../config/datawenjia_new.txt', 'w') as whrite_fp:
        tag = False
        for read_line in read_fp:
            if read_line.strip() == user_data:  # url mkw
                tag = True
                continue
            if tag and read_line.strip().startswith('url'):
                tag = False
            if not tag:
                whrite_fp.write(read_line)
        else:
            has_write = True
            if has_write:
                whrite_fp.write(user_data + "\n")
                for new_line in new_res:
                    whrite_fp.write("   " + new_line + "\n")
                has_write = False
    os.remove('../config/datawenjia.txt')
    os.renames('../config/datawenjia_new.txt', '../config/datawenjia.txt')

def delete():
    pass
def insert():
    pass
def exit():
    pass

if __name__ == '__main__':
    msg='''
    1.查询
    2.修改
    3.删除
    4.插入
    5.退出
    '''
    msg_dict={
        '1':fetch,
        '2':rechange,
        '3':delete,
        '4':insert,
        '5':exit}
    while True:
        print(msg)
        choice = input('请输入你的选择').strip()
        if not choice:continue
        if choice ==5:break
        data = input('用户的数据')
        if choice !='1':
            data = eval(data)
        res= msg_dict[choice](data)
        print('最终结果是：',res)